layui.define(function(exports){ //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
  var taskWeeklyPage = {
    render: function(){
    	var $ = layui.$,
    	table = layui.table,
    	layer = layui.layer,
    	form = layui.form,
    	selectN = layui.selectN,
        selectM = layui.selectM,
    	laydate = layui.laydate,
    	element = layui.element,
    	windowSize = {width:'700px',height:'600px'},
    	dateFormat = /[0-9]{4}-[0-9]{1,}-[0-9]{1,}/;
    	var optName;
    	var tableObj = table.render({
    	  id: 'main-table',
    	  elem: '#table', //指定原始表格元素选择器（推荐id选择器）
    	  url: '/boss/task/query_weekly_list',
    	  method:'post',
    	  size: 'sm',
    	  autoSort : false,
		  even: false,
    	  toolbar: '#toolbar',
    	  height: 'full-70',
    	  limits : [10,30,50,100],
    	  limit: 30,
    	  page: true,
    	  cols: [[
    		  {type:'checkbox'},
    		  {field: 'nick', title: '责任人',sort:false,width:100,templet: function(d){
    			  switch(d.nick) {
    			  	case null:
    			  		return '--';
    			  	case '':
    			  		return '';
    			  	default:
    			  		return d.nick;
    			  }
    	      }},
    		  {field: 'projectName', title: '项目',sort:false,width:150,templet: function(d){
    			  switch(d.projectName) {
    			  	case null:
    			  		return '--';
    			  	case '':
    			  		return '';
    			  	default:
    			  		return d.projectName;
    			  }
    	      }},
    		  {field: 'name', title: '任务信息',sort:false,templet: function(d){
    			  switch(d.name) {
    			  	case null:
    			  		return '--';
    			  	case '':
    			  		return '';
    			  	default:
    			  		return d.name;
    			  }
    	      }},
    		  {field: 'codeStart', title: '任务开始时间',sort:false,width:110,templet: function(d){
    			  switch(d.codeStart) {
    			  	case null:
    			  		return '--';
    			  	case '':
    			  		return '';
    			  	default:
    			  		return d.codeStart.match(dateFormat);
    			  }
    	      }},
    		  {field: 'codeEnd', title: '任务完成时间',sort:false,width:110,templet: function(d){
    			  switch(d.codeEnd) {
    			  	case null:
    			  		return '--';
    			  	case '':
    			  		return '';
    			  	default:
    			  		return d.codeEnd.match(dateFormat);
    			  }
    	      }},
    		  {field: 'timeCost', title: '耗费工时',sort:false,width:80,templet: function(d){
    			  switch(d.timeCost) {
    			  	case null:
    			  		return '--';
    			  	case '':
    			  		return '';
    			  	default:
    			  		return d.timeCost/8.0 > 1?d.timeCost/8.0+' 天':d.timeCost+' 小时';
    			  }
    	      }},
    	      {field: 'progress', title: '进度',sort:false,width:100,templet: function(d){
    			  switch(d.progress) {
    			  	case null:
    			  		return '--';
    			  	case '':
    			  		return '';
    			  	default:
    			  		color = 'layui-bg-blue';
				  		if(d.progress == 100){
				  			color ='layui-bg-green';
				  		}
    			  		return '<div class="layui-progress layui-progress-big" lay-showPercent="true">'+
			    			  	  '<div class="layui-progress-bar '+color+'" lay-percent="'+d.progress+'%"></div>'+
			    			  	'</div>';
    			  }
    	      }},
    		  {field: 'status', title: '任务状态',sort:false,align:'center',width:100,templet: function(d){
    			  switch(d.status) {
    			  	case null:
    			  		return '--';
    			  	case '':
    			  		return '';
    			  	case 'pending':
    			  		return '<span class="layui-badge layui-bg-red">挂起</span>';
    			  	case 'run':
    			  		return '<span class="layui-badge layui-bg-blue">进行中</span>';
    			  	case 'finish':
    			  		return '<span class="layui-badge layui-bg-green">已完成</span>';
    			  	case 'cancel':
    			  		return '<span class="layui-badge layui-bg-black">撤销</span>';
    			  	case 'plan':
    			  		return '<span class="layui-badge layui-bg-orange">计划</span>';
    			  	default:
    			  		return d.status;
    			  }
    	      }},
//    		  {field: 'pendingReson', title: '挂起原因',sort:false,templet: function(d){
//    			  switch(d.pendingReson) {
//    			  	case null:
//    			  		return '--';
//    			  	case '':
//    			  		return '';
//    			  	default:
//    			  		return d.pendingReson;
//    			  }
//    	      }},
    	      {field: 'remarkTask', title: '备注',sort:false,templet: function(d){
    			  switch(d.remarkTask) {
    			  	case null:
    			  		return '--';
    			  	case '':
    			  		return '';
    			  	default:
    			  		return d.remarkTask;
    			  }
    	      }},
    	      {field: 'updateTime', title: '更新时间',sort:false,width:100,templet: function(d){
    	    	  switch(d.updateTime) {
    	    	  case null:
    	    		  return '--';
    	    	  case '':
    	    		  return '';
    	    	  default:
    	    		  return d.updateTime.match(dateFormat);
    	    	  }
    	      }},
    		  {fixed: 'right', title:'操作', toolbar: '#optbar', width:165}
    	  ]],
    	  done: function(res, curr, count){
    		  merge(res);
    		  element.render();
		  }
    	});
    	function merge(res) {
            
            var data = res.data;
            var mergeIndex = 0;//定位需要添加合并属性的行数
            var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
            var columsName = ['nick','projectName'];//需要合并的列名称
            var columsIndex = [1,2];//需要合并的列索引值
        
            for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
                var trArr = $(".layui-table-body>.layui-table").find("tr");//所有行
                    for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
                        var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                        var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
                        
                        if (data[i][columsName[k]] === data[i-1][columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
                            mark += 1;
                            tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                                $(this).attr("rowspan", mark);
                            });
                            tdCurArr.each(function () {//当前行隐藏
                                $(this).css("display", "none");
                            });
                        }else {
                            mergeIndex = i;
                            mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                        }
                    }
                mergeIndex = 0;
                mark = 1;
            }
        }
    	/** 顶部toolbar事件 **/
    	table.on('toolbar(table)', function(obj){
    		switch(obj.event){
    		  case 'refresh-opt':
  			    tableObj.reload();
  			  break;
    		  case 'export-file-opt':
    			  var exportUrl = '/boss/task/export-weekly-report';
    			  var param = new Array();
    			  if($('#codeStartStrStart').val() != ''){
    				  param.push('codeStartStrStart='+$('#codeStartStrStart').val());
    			  }
    			  if($('#codeEndStrEnd').val() != ''){
    				  param.push('codeEndStrEnd='+$('#codeEndStrEnd').val());
    			  }
    			  if($('#userId').val() != ''){
    				  param.push('userId='+$('#userId').val());
    			  }
    			  if($('#projectId').val() != ''){
    				  param.push('projectId='+$('#projectId').val());
    			  }
    			  if($('input[name=status]').val() != ''){
    				  param.push('status='+$('input[name=status]').val());
    			  }
    			  $.each(param,function(i,item){
    				  if(i == 0){
    					  exportUrl += '?'+item;
    				  } else {
    					  exportUrl += '&'+item;
    				  }
    			  });
    			  window.open(exportUrl);
   			  break;
    		  case 'addData-opt':
    			  var data = obj.data;
    			  optName = 'new';
    			  layer.open({
    				  type: 1,
    				  area: [windowSize.width,windowSize.height],
    				  title : '新增/添加',
    				  content: $('#windows'),
    				  resize : false,
    				  move : false,
    				  shadeClose : false,
    				  btn : [ '确定', '取消' ],
    				  success : function(layero, index){
    					  $('#win-form')[0].reset();
    				  },
					  yes : function(index, layero) {
						  $('#win-submit').trigger('click');
					  }
    				});
		      break;
    		  case 'batch-del-opt':
    			  var checkStatus = table.checkStatus('main-table');
    			  if(checkStatus.data.length ==0){
    				  layer.alert('请先选择待删除行',{icon: 5});
    				  return;
    			  }
    			  layer.confirm("你确定批量删除"+checkStatus.data.length+"个项目吗？", {icon: 3, title:'提示'},
    			            function(index){//确定回调
        				  		var keys = new Array();
        				  		$.each(checkStatus.data,function(i,item){
        				  			keys.push(item.id);
        				  		});
        				  		batchDelete(keys,index);
    			            },function (index) {//取消回调
    			               layer.close(index);
    			            }
    			        );
    			  break;
    		}
    	});
    	
    	form.on('submit(win-submit)', function(data){
  		  $.ajax({
  			    type: 'POST',
  			    url: optName=='new'?'/boss/task/add_item':'/boss/task/update_item',
  			    data: data.field,
  			    success: function (data) {
  			        if(data.success){
  			        	layer.closeAll();
  			        	tableObj.reload();
  			        	layer.msg(data.message);
  			        }else{
  			            layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
  			        }
  			    },
  			    error: function(data) {
  			        layer.msg(data.responseJSON.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
  			    },
  			    dataType: "json"
  			});
  		  return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
  		});
    	
    	/** 右侧tool事件 **/
    	table.on('tool(table)', function(obj){
    		var data = obj.data;
    		switch(obj.event){
    		  case 'edit-opt':
    			  optName = 'update';
    			  layer.open({
    				  type: 1,
    				  area: [windowSize.width,windowSize.height],
    				  title : '编辑',
    				  content: $('#windows'),
    				  shadeClose : false,
    				  move : false,
    				  btn : [ '确定', '取消' ],
    				  success : function(layero, index){
    					  $('#win-form')[0].reset();
    					  $.post(
    							  "/boss/task/get_item_by_key",
    							  {id:data.id},
    							  function(data, textStatus, jqXHR){
    								  form.val("win-form",data);
    							  },"json");
    				  },
					  yes : function(index, layero) {
						  $('#win-submit').trigger('click');
					  }
    				});
    			  break;
    		  case 'view-opt':
    			  optName = 'view';
    			  layer.open({
    				  type: 1,
    				  area: [windowSize.width,windowSize.height],
    				  title : '查看',
    				  content: $('#windows'),
    				  shadeClose : false,
    				  move : false,
    				  btn : [ '关闭'],
    				  success : function(layero, index){
    					  $('#win-form')[0].reset();
    					  $.post(
    							  "/boss/task/get_item_by_key",
    							  {id:data.id},
    							  function(data, textStatus, jqXHR){
    								  form.val("win-form",data);
    							  },"json");
    				  },
    				  btn1 : function(index, layero) {
    					  layer.closeAll();
					  }
    				});
    			  break;
    		  case 'del-opt':
    			  layer.confirm("你确定删除项目“"+obj.data.name+"”吗？", {icon: 3, title:'提示'},
  			            function(index){//确定回调
      				  		var keys = new Array();
      				  		keys.push(obj.data.id);
      				  		batchDelete(keys,index);
  			            },function (index) {//取消回调
  			               layer.close(index);
  			            }
  			        );
    			  break;
    		}
    	});
    	
    	form.on('submit(search-opt)',function(data){
    		tableObj.reload({where:data.field});
    	    return false;
    	});
    	
    	$('#search-more').click(function(){
    		layer.open({
				  type: 1,
				  area: ['1024px','468px'],
				  title : '更多查询条件',
				  content: $('#windows-search'),
				  resize : true,
				  shadeClose : true,
				  shade : false,
				  btn : [ '查询', '关闭' ],
				  success : function(layero, index){
				  },
				  yes : function(index, layero) {
					tableObj.reload({where:form.val('win-search-form')});
				  }
				});
    	});
    	
    	function batchDelete(keys,index){
    		$.ajax({
	                type: 'POST',
	                url: '/boss/task/delete_item',
	                data: JSON.stringify(keys),
	                success: function (data) {
	                    if(data.success){
	                        layer.close(index);
	                    }else{
	                        layer.msg(data.message,{icon: 5,anim: 6,time: 0,btn:['确定']});
	                    }
	                    tableObj.reload();
	                    layer.msg(data.message);
	                },
	                error: function(data) {
	                    layer.msg(data.responseText,{icon: 5,anim: 6,title:'错误',time: 0,btn:['确定']});
	                },
	                contentType: "application/json",
	                dataType: "json"
	            });
    	}
    	laydate.render({
		    elem: '#codeStartStrStart'
		  });
    	laydate.render({
		    elem: '#codeStartStrEnd'
		  });
    	laydate.render({
		    elem: '#codeStartStrStart-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#codeStartStrEnd-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#codeStart-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#codeEndStrStart'
		  });
    	laydate.render({
		    elem: '#codeEndStrEnd'
		  });
    	laydate.render({
		    elem: '#codeEndStrStart-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#codeEndStrEnd-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#codeEnd-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#createTimeStrStart',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#createTimeStrEnd',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#createTimeStrStart-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#createTimeStrEnd-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#createTime-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTimeStrStart',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTimeStrEnd',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTimeStrStart-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTimeStrEnd-win',
		    type: 'datetime'
		  });
    	laydate.render({
		    elem: '#updateTime-win',
		    type: 'datetime'
		  });
    	var tagIns1 = selectM({
    	      //元素容器【必填】
    	      elem: '#status'
    	      //候选数据【必填】
    	      ,data: '/boss/task/task-status-list'
    	      ,max:3
    	      ,width:250
    	      ,tips:'请选择任务状态'
    	    }); 
    	
    }
  };
  
  //输出test接口
  exports('taskWeeklyPage', taskWeeklyPage);
});